package com.dxy.netty.handlerchain;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @Description netty客户端
 * @author xiao tang
 * @version 1.0.0
 * @createTime 2022年09月10日
 */
public class NettyHandlerChainClient {

    private final String host;
    private final int port;

    public NettyHandlerChainClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) {
        try {
            new NettyHandlerChainClient("localhost", 8089).run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void run() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new NettyClientInitializer());  // 自定义一个初始化类
            // 连接服务器
            ChannelFuture channelFuture = bootstrap.connect(this.host, this.port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    /**
     * @Description netty客户端初始化器
     * @author xiao tang
     * @version 1.0.0
     * @createTime 2022年09月10日
     */
    static class NettyClientInitializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            // 出站handler，把long型数据解码为字节型
            pipeline.addLast(new MyLong2ByteEncoder());

            // 入站handler，把字节型数据解码为long型
            pipeline.addLast(new MyByte2LongDecoder());

            // 添加一个自定义handler（入站），处理业务逻辑
            pipeline.addLast(new NettyHandlerChainClientHandler());
        }
    }
}
